package com.dm.dao.impl;

import com.dm.dao.BaseDao;
import com.dm.dao.UserDao;
import com.dm.dto.input.UserDto;
import com.dm.entity.User;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import org.hibernate.Query;

import java.util.List;

/**
 * @author hqw521@qq.com
 * @date 2018/11/15 12:05
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private BaseDao baseDao;

    @Override
    public Long checkUsername(String username) {
        String hql = "select count(1) from User dm where dm.userName = '" + username + "'";
        Query query = baseDao.getSession().createQuery(hql);
        return (Long) query.iterate().next();

    }

    @Override
    public UserDto selectUser(UserDto userDto) {
        String sql = "SELECT\n" +
                "\tdu.user_id userId,\n" +
                "\tdu.user_name userName,\n" +
                "\tdu.user_type userType\n" +
                "FROM\n" +
                "\tdm_user du\n" +
                "WHERE\n" +
                "\tdu.user_name = '" + userDto.getUserName() + "'\n" +
                "AND du.password = '" + userDto.getPassword() + "'";
        Query query = baseDao.getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(UserDto.class));

        return (UserDto) query.uniqueResult();
    }

    @Override
    public Integer insertUser(UserDto userDto) {
        String sql = "insert into dm_user (user_name, password) values(?, ?)";
        Query query = baseDao.getSession().createSQLQuery(sql);
        query.setString(0, userDto.getUserName());
        query.setString(1, userDto.getPassword());
        return query.executeUpdate();
    }

    @Override
    public List<UserDto> findAllUser() {
        String sql = "select du.user_id userId, du.user_name userName from dm_user du";
        Query query = baseDao.getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(UserDto.class));
        List<UserDto> list = query.list();
        return list;
    }
}
